package br.pucrs.lognplay.job;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import br.pucrs.lognplay.entity.DynamicView;
import br.pucrs.lognplay.repository.DynamicViewRepository;
import br.pucrs.lognplay.repository.RepositoryManager;

public class StorerControllerJob implements Job {

	private static final Logger logger = Logger.getLogger(StorerControllerJob.class);

	private static final String STORER_JOB_NAME = "STORER_JOB_NAME";

	private static final String STORER_TRIGGER_NAME = "STORER_TRIGGER_NAME";

	private static final String STORER_GROUP_NAME = "STORER_GROUP_NAME";

	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		logger.trace("=== Executing StorerControllerJob...");

		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

			RepositoryManager.beginTransaction();
			DynamicViewRepository dynamicViewRepository = RepositoryManager.getDynamicViewRepository();
			List<DynamicView> dynamicViews = dynamicViewRepository.listAll();
			RepositoryManager.commitTransaction();

			if (dynamicViews.size() > 0) {
				for (DynamicView dynamicView : dynamicViews) {

					logger.trace("Processing dynamic view id: " + dynamicView.getId());

					// @formatter:off
					JobDetail dynamicIndexerJob = newJob(StorerJob.class)
							//.withIdentity(STORER_JOB_NAME + "#" + dynamicView.getId(), STORER_GROUP_NAME)
							.withIdentity(STORER_JOB_NAME + "#" + System.currentTimeMillis(), STORER_GROUP_NAME)
							.build();
	
					Trigger dynamicIndexerTrigger = newTrigger()
							//.withIdentity(STORER_TRIGGER_NAME + "#" + dynamicView.getId(), STORER_GROUP_NAME)
							.withIdentity(STORER_TRIGGER_NAME + "#" + System.currentTimeMillis() , STORER_GROUP_NAME)
							.startNow()
							.build();
					// @formatter:on

					if (!scheduler.checkExists(dynamicIndexerJob.getKey())) {
						dynamicIndexerJob.getJobDataMap().put(StorerJob.DYNAMIC_VIEW_ID_PARAMETER, dynamicView.getId());
						scheduler.scheduleJob(dynamicIndexerJob, dynamicIndexerTrigger);
					}
				}
			} else {
				logger.trace("No dynamic views to process!");
			}

		} catch (Exception e) {
			logger.error(e);
		}

		logger.trace("=== StorerControllerJob terminated!");
	}

}
